package controller

import (
	"crypto/md5"
	"fmt"
	"github.com/labstack/echo/v4"
	"github.com/labstack/gommon/log"
	"io/ioutil"
	"law_case_api/models"
	"law_case_api/services"
	"law_case_api/utils"
	"net/http"
	"strconv"
	"strings"
	"time"
)

// @Summary 文件上传
// @Tags 文件系统
// @Accept plain
// @Produce plain
// @Success 200 {object} models.BaseResult
// @Failure 400 {object} models.BaseResult
// @Router /wzj/file/upload [post]
func UploadFile(c echo.Context) error {
	resp := models.BaseResult{
		Code: 200,
	}
	// Source
	fileHeader, err := c.FormFile("file")
	if err != nil {
		resp.Code = 400
		resp.Message = err.Error()
		return c.JSON(http.StatusOK, resp)
	}
	fReader, _ := fileHeader.Open()
	fileByte, _ := ioutil.ReadAll(fReader)
	//fileSize := int64(len(fileByte))
	md5Str := strconv.FormatInt(time.Now().UnixNano(), 10) + fileHeader.Filename
	has := md5.Sum([]byte(md5Str))
	filePathArry := strings.Split(fileHeader.Filename, ".")
	fileMd5 := ""
	if len(filePathArry) > 0 {
		fileMd5 = fmt.Sprintf("%x.%s", has, filePathArry[len(filePathArry)-1])
	} else {
		fileMd5 = fmt.Sprintf("%x", has)
	}

	key, err := utils.QiNiuUploadByte(fileMd5, fileByte)
	if err != nil {
		resp.Code = 400
		resp.Message = err.Error()
		return c.JSON(http.StatusOK, resp)
	}

	//文件信息保存到数据库
	wzjFile := models.WzjFile{
		FileName: fileHeader.Filename,
		FilePath: fmt.Sprintf("%s/%s", utils.DOMAIN, key),
	}
	_file := services.FileService{}
	_, _wzjFile, err := _file.CreateFile(wzjFile)
	if err != nil {
		log.Error("创建文件上传记录失败", err)
		resp.Code = 400
		resp.Message = "创建文件上传记录失败"
		return c.JSON(http.StatusOK, resp)
	}
	if _wzjFile.Id > 0 {
		resp.Data = _wzjFile.Id
		return c.JSON(http.StatusOK, resp)
	}
	resp.Code = 400
	resp.Message = "创建文件上传记录失败"
	return c.JSON(http.StatusOK, resp)
}

// @Summary 根据文件id获取文件详情
// @Tags 文件系统
// @Accept plain
// @Produce plain
// @Param fileId query string true "文件id"
// @Success 200 {object} models.BaseResult
// @Failure 400 {object} models.BaseResult
// @Router /wzj/file/get [get]
func GetFileInfo(c echo.Context) error {
	resp := models.BaseResult{
		Code: 200,
	}
	fileId, _ := strconv.Atoi(c.QueryParam("fileId"))
	if fileId == 0 {
		resp.Code = 400
		resp.Message = "文件编号不能为空"
		return c.JSON(http.StatusOK, resp)
	}
	_file := services.FileService{}
	_wzjFile, err := _file.GetFileById(fileId)
	if err != nil {
		resp.Code = 400
		resp.Message = "查询文件失败"
		return c.JSON(http.StatusOK, resp)
	}
	if _wzjFile.Id > 0 {
		resp.Data = _wzjFile.FilePath
		return c.JSON(http.StatusOK, resp)
	}
	resp.Code = 400
	resp.Message = "文件不存在，请重新上传文件"
	return c.JSON(http.StatusOK, resp)
}
